<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请输入工厂"
            clearable
            @keyup.enter="search"
            @change="closeDialog(searchParam.plantId)"
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            v-model="searchParam.workCenterId"
            placeholder="请选择工作中心"
            :disabled="searchParam.plantId === ''"
            clearable
            @keyup.enter="search"
          >
            <el-option
              v-for="item in workshopList"
              :key="item.id"
              :label="`${item.workshopCode}-${item.workshopName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划批次">
          <el-input
            v-model="searchParam.planBatch"
            placeholder="请输入计划批次"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="searchParam.planDateSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            @change="getplanDate"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchParam.orderState"
            placeholder="请选择订单状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('ProduceOrderState')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="confirmList()"
          >批量关闭</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="工作中心"
          prop="workCenterName"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.workCenterCode }}-{{ scope.row.workCenterName }}
          </template>
        </el-table-column>
        <el-table-column
          label="计划批次"
          prop="planBatch"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="计划日期"
          prop="planDate"
          value-format="YYYY-MM-DD"
          min-width="180"
          show-overflow-tooltip
          :formatter="formatDate"
          align="center"
        />
        <el-table-column
          label="班次开始时间"
          prop="shiftTimeBegin"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="班次结束时间"
          prop="shiftTimeEnd"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="计划数量"
          prop="planQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="已完成数量"
          prop="planFinishQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="数量单位"
          prop="quantityUnit"
          min-width="100"
          align="left"
        >
          <template #default="scope">
            {{ useDictionary("MeasurementUnit", scope.row.quantityUnit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="订单状态"
          prop="orderState"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("ProduceOrderState", scope.row.orderState) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>

            <el-button
              type="primary"
              size="small"
              plain
              :disabled="scope.row.orderState != 2 && scope.row.orderState != 3"
              link
              @click="confirmList(scope.row.id)"
            >
              关闭
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesworkorderplan-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESWORKORDERPLAN",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesworkorderplan/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  planDateSearch: [],
  planDateStart: "",
  planDateEnd: "",
  planBatch: "",
  orderState: "",
  plantId: "",
  workCenterId: "",
};

const deleteParam = {
  api: "/mes/mesworkorderplan/closePlan",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlantList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesworkorderplan/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开加工单计划明细表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改加工单计划明细";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增加工单计划明细";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开加工单计划明细表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "加工单计划明细详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getplanDate(data: any) {
  if (data) {
    searchParam.value.planDateStart = data[0];
    searchParam.value.planDateEnd = data[1];
  } else {
    searchParam.value.planDateStart = "";
    searchParam.value.planDateEnd = "";
  }
}
//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}

//批量关闭
const confirmList = async (id?: string) => {
  if (id) {
    ids.value = [id];
  }
  ElMessageBox.confirm("确认对已选中的数据项进行关闭吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res: any = await request({
      url: "/mes/mesworkorderplan/closePlan",
      method: "post",
      data: { ids: ids.value },
    });
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "批量关闭成功",
      });
    }
    getTableList();
  });
};
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
  searchParam.value.plantId = plantList.value[0].id;
  closeDialog(searchParam.plantId);
};
function closeDialog(plantId: String) {
  getWorkshopList(plantId);
  searchParam.value = { ...searchParam.value, workCenterId: "" };
}
//工作中心
const workshopList = ref([]);
const getWorkshopList = async (plantId: String) => {
  const { data } = await request({
    url: "mes/mesworkshop/getList",
    method: "post",
    data: { plantId: plantId },
  });
  workshopList.value = data;
};
</script>
<style lang="scss" scoped>
:deep(.el-form .el-form-item__label) {
  width: 63px;
}
</style>
